import { createStore } from "vuex"
import { userinfoRequest } from '../api/user'
import { articleCatesRequest } from "../api/article"
import { ElMessage } from "element-plus"

// 创建 store 实例
const store = createStore({
  namespaced: true,
  state() {
    return {
      // 登录状态
      isAuthenticated: window.localStorage.getItem('token') ? true : false,
      // 菜单的激活状态
      activePath: window.localStorage.getItem('menuAction') || 'welcome',
      // 用户的基本信息
      userinfo: {},
      // 文章分类列表
      articleCates: []
    }
  },
  mutations: {
    // 修改登录状态
    setIsAuthenticated(state, payLoad) {
      state.isAuthenticated = payLoad
    },
    // 修改菜单激活状态
    setActivePath(state, payLoad) {
      state.activePath = payLoad
    },
    // 修改用户的基本信息
    setUserinfo(state, payLoad) {
      state.userinfo = payLoad
    },
    // 修改文章分类列表
    setArticleCates(state, payLoad) {
      state.articleCates = payLoad
    }
  },
  actions: {
    // 用户基本信息请求
    async getUserinfoRequest(context, params) {
      const { data: res } = await userinfoRequest()
      // console.log(res)
      const { status, message, data } = res
      if (status === 0) {
        context.commit('setUserinfo', data)
      } else {
        ElMessage.error(message)
      }
    },
    // 获取文章分类数据
    async getarticleCatesRequest(context, params) {
      const { data: res } = await articleCatesRequest()
      const { status, message, data } = res
      if (status === 0) {
        context.commit('setArticleCates', data)
      } else {
        ElMessage.error(message)
      }
    }
  }
})

// 将 store 实例暴露出去
export default store